package org.lql.algo.codecrush.hot100.substring;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * @author: liangqinglong
 * @date: 2025-10-15 15:09
 * @description: 239. 滑动窗口最大值 <a href="https://leetcode.cn/problems/sliding-window-maximum/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class MaxSlidingWindow {

	public int[] maxSlidingWindow(int[] nums, int k) {
		if (nums == null || nums.length == 0 || k < 0) {
			return new int[0];
		}
		Deque<Integer> queue = new ArrayDeque<>();
		int n = nums.length;
		int[] ans = new int[n - k + 1];
		for (int i = 0; i < n; i++) {

			while (!queue.isEmpty() && queue.peekFirst() < i - k + 1) {
				queue.pollFirst();
			}

			while (!queue.isEmpty() && nums[queue.peekLast()] < nums[i]) {
				queue.pollLast();
			}

			queue.push(i);
			if (i >= k - 1) {
				ans[i - k + 1] = nums[queue.peekLast()];
			}

		}
		return ans;
	}

	public static void main(String[] args) {
		MaxSlidingWindow maxSlidingWindow = new MaxSlidingWindow();
		int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
		int k = 3;
		int[] ints = maxSlidingWindow.maxSlidingWindow(nums, k);
		System.out.println(Arrays.toString(ints));
	}
}
